package com.dingpeikeji.quickdeer.modules.wx.share;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.CacheUtils;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.modules.cupons.service.TCuponsService;
import com.dingpeikeji.quickdeer.core.modules.line.entity.TLine;
import com.dingpeikeji.quickdeer.core.modules.line.service.TLineService;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.orders.service.TOrdersService;
import com.dingpeikeji.quickdeer.core.modules.site.entity.TSitedtl;
import com.dingpeikeji.quickdeer.core.modules.site.service.TSitedtlService;
import com.dingpeikeji.quickdeer.mobile.service.OrderService;
import com.dingpeikeji.quickdeer.modules.base.service.FrontUserService;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.ShareRentproduct;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TCargotype;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentgroup;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentproduct;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FRentproductService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.RentproductOrderService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.ShareProductService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TCargotypeService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentgroupService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentproductService;
import com.dingpeikeji.quickdeer.utils.BackResult;

@Controller
@RequestMapping("${wxPath}/share")
public class WxShareController {
	@Autowired
	private TRentproductService tRentproductService;
	@Autowired
	private TLineService lineService;
	@Autowired
	private TOrdersService ordersService;
	@Autowired
	private TSitedtlService tSitedtlService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private FRentproductService rentproductService;
	@Autowired
	private TRentgroupService tRentgroupService;
	@Autowired
	private TCuponsService tCuponsService;
	@Autowired
	private FrontUserService frontUserService;
	@Autowired
	private ShareProductService shareProductService;
	@Autowired
	private RentproductOrderService rentproductOrderService;
	@Autowired
	private TOrdersService tOrdersService;
	@Autowired
	private TCargotypeService tCargotypeService;
	@Autowired
	private TCuponsService cuponsService;

	@RequestMapping("toShare")
	public String toShare(Model model,String shareName,String seats, 
			String totalPrice,String userid,String rentid,String cuponsId,String boardaddr,String fromdate) {
		model.addAttribute("shareName", shareName);
		model.addAttribute("seats", seats);
		model.addAttribute("totalPrice", totalPrice);
		model.addAttribute("avgPrice", Math.ceil(Double.parseDouble(totalPrice)/Double.parseDouble(seats)));
		model.addAttribute("rentid", rentid);
		model.addAttribute("cuponsId", cuponsId);
		model.addAttribute("boardaddr", boardaddr);
		model.addAttribute("fromdate", fromdate);
		return "wx/modules/ShareProduct/shareBook";
	}
	@RequestMapping("toAirShare")
	public String toAirShare(Model model,String fromdate,String abbr,String productname,String officename,
			String suitrtnprice,String userid,String cuponsId,String departsiteName,String destsiteName,
			String boardaddr,String cargotype) {
		model.addAttribute("cuponsId", cuponsId);
		model.addAttribute("boardaddr", boardaddr);
		model.addAttribute("fromdate", fromdate);
		model.addAttribute("abbr", abbr);
		model.addAttribute("officename", officename);
		model.addAttribute("productname", productname);
		model.addAttribute("seats", tCargotypeService.get(cargotype).getSeats());
		model.addAttribute("suitrtnprice", suitrtnprice);
		model.addAttribute("avgPrice", Math.ceil(Double.parseDouble(suitrtnprice)/tCargotypeService.get(cargotype).getSeats()));
		model.addAttribute("departsite", tSitedtlService.getSiteByName(departsiteName));
		model.addAttribute("destsite", tSitedtlService.getSiteByName(destsiteName));
		model.addAttribute("cargotype", cargotype);
		return "wx/modules/ShareProduct/shareAirBook";
	}
	@RequestMapping("toShareBooking")
	public String toShareBooking(Model model,String sid,String avgprice) {
		return "wx/modules/ShareProduct/shareBooking";
	}
	// 拼车列表
	@RequestMapping(value = "shareList")
	public String getShareList(HttpServletRequest request, HttpServletResponse response,
			ShareRentproduct shareRentproduct, Integer pageNo, Integer pageSize,Model model) {
		// 分页查询
		Page<ShareRentproduct> page = new Page<ShareRentproduct>(request, response);
		page.setPageNo(1);
		page.setPageSize(500);
		if ("0".equals(shareRentproduct.getDepartsite())||StringUtils.isEmpty(shareRentproduct.getDepartsite())) {
			shareRentproduct.setDepartsite(null);
		}
		if ("0".equals(shareRentproduct.getDestsite())||StringUtils.isEmpty(shareRentproduct.getDestsite())) {
			shareRentproduct.setDestsite(null);
		}
		page = shareProductService.findPage(page, shareRentproduct);
		for (ShareRentproduct sr : page.getList()) {
			sr.setFromdateStr(DateUtils.formatDateTime(sr.getFromdate()));
			if (!sr.getLinepic().contains("https://")) {
				sr.setLinepic("https://www.xiakeyueche.com"+sr.getLinepic());
			}
		}
		if (page.getCount() == 0) {
			model.addAttribute("mes", "暂无有效拼车产品");
			return "wx/modules/ShareProduct/shareIndex";
		}
		// 出发地集合
		Set<Map<String, String>> departSet = new HashSet<Map<String, String>>();
		List<String> departList = shareProductService.getDepartList();
		if (departList!=null&&departList.size()>0) {
			for (String sr : departList) {
				TSitedtl depart = tSitedtlService.get(sr);
				Map<String, String> departMap = new HashMap<String, String>();
				departMap.put("siteid", depart.getSiteid());
				departMap.put("sitename", depart.getSitename());
				departSet.add(departMap);
			}
		}
		// 目的地集合
		Set<Map<String, String>> destSet = new HashSet<Map<String, String>>();
		List<String> destList = shareProductService.getDestList();
		if (destList!=null&&destList.size()>0) {
			for (String sr : destList) {
				Map<String, String> destMap = new HashMap<String, String>();
				TSitedtl dest = tSitedtlService.get(sr);
				destMap.put("siteid", dest.getSiteid());
				destMap.put("sitename", dest.getSitename());
				destSet.add(destMap);
			}
		}
		if (shareRentproduct.getDepartsite()!=null) {
			model.addAttribute("departName", tSitedtlService.get(shareRentproduct.getDepartsite()).getSitename());
			model.addAttribute("departId", shareRentproduct.getDepartsite());
		}
		if (shareRentproduct.getDestsite()!=null) {
			model.addAttribute("destName", tSitedtlService.get(shareRentproduct.getDestsite()).getSitename());
			model.addAttribute("destId", shareRentproduct.getDestsite());
		}
		model.addAttribute("departSet",departSet);
		model.addAttribute("destSet", destSet);
		model.addAttribute("shareList", page.getList());
		return "wx/modules/ShareProduct/shareIndex";
	}

	// 查看拼车
	@RequestMapping(value = "getShareDetailById")
	public String getShareDetailById(HttpServletRequest request, String sid,Model model) {
		ShareRentproduct shareRentproduct = shareProductService.getElseInfo(sid);
		if (shareRentproduct == null) {
			model.addAttribute("mes", "查询产品信息失败");
			return "wx/modules/ShareProduct/shareDetail";
		}
		if (shareRentproduct.getCurrentsell().equals(shareRentproduct.getMinamount())) {
			model.addAttribute("mes1", "参团人数已满,不可预订");
		}
		// 处理线路描述
		if (ShareRentproduct.SHARE_TYPE_TRAVEL.equals(shareRentproduct.getSharetype())) {
			if (shareRentproduct.gettRentgroup()!=null) {
				String description = shareRentproduct.gettRentgroup().getDescription();
				description = description.replaceAll("&nbsp;", "");
				String[] arr = description.split("第" + "\\S" + "天");
				description = description.replaceAll("&nbsp;", "");
				Map<String, String> descriptions = new HashMap<String, String>();
				formatDesc(arr, descriptions);
				model.addAttribute("descriptions", descriptions);
			}
		}
		// 计算该产品失效剩余时间
		Date afterDate = shareRentproduct.getEnddate();
		Date beforeDate = new Date();
		// 时间差
		long distanceOfTwoDate = DateUtils.getDistanceMilesOfTwoDate(beforeDate, afterDate);
		String time = DateUtils.formatMileToTime(distanceOfTwoDate);
		if ("2".equals(shareRentproduct.getStatus())) {
			model.addAttribute("surplusTime", "报名截止");
		} else {
			model.addAttribute("surplusTime", "报名还剩" + time);
		}
		if (!shareRentproduct.getLinepic().contains("https://")) {
			shareRentproduct.setLinepic("https://www.xiakeyueche.com"+shareRentproduct.getLinepic());
		}
		model.addAttribute("cartype", shareRentproduct.gettCargotype().getTypename());
		model.addAttribute("createDateStr",DateUtils.formatDate(shareRentproduct.getCreateDate()));
		model.addAttribute("fromDateStr",DateUtils.formatDate(shareRentproduct.getFromdate()));
		model.addAttribute("office", shareRentproduct.getOffice());
		model.addAttribute("shareProduct", shareRentproduct);
		model.addAttribute("createManImage", shareRentproduct.getUser().getUserimage());
		model.addAttribute("createManName", shareRentproduct.getUser().getName());
		if (ShareRentproduct.SHARE_TYPE_AIR.equals(shareRentproduct.getSharetype())) {
			model.addAttribute("shareFee", ShareRentproduct.SHARE_FEE_Air);
		} else {
			model.addAttribute("shareFee", ShareRentproduct.SHARE_FEE);
		}
		//春节拼车处理
		String productname = shareRentproduct.getProductname();
		if(productname.contains("大学城")){
			productname = productname.substring(0,productname.length()-4);
			//获取线路描述
			TLine tLine = lineService.getLineByName(productname);
			String description = tLine.getDescription();
			description = description.replaceAll("&nbsp;", "");
			String[] arr = description.split("第"+"\\S"+"天");
			description = description.replaceAll("&nbsp;", "");
			Map<String, String> descriptions = new HashMap<String, String>();
			formatDesc(arr, descriptions);
			//霞客约车
			shareRentproduct.getOffice().setAbbr("霞客约车");
			shareRentproduct.getOffice().setName("霞客约车");
			model.addAttribute("descriptions", descriptions);
			model.addAttribute("shareFee", null);
			model.addAttribute("createManName", "霞客约车");
		}
		model.addAttribute("shareNotes", ShareRentproduct.SHARE_NOTES);
		return "wx/modules/ShareProduct/shareDetail";
	}

	private List<Long> formatDesc(String[] arr, Map<String, String> map) {
		List<Long> list = new ArrayList<Long>();
		long i = 1;
		for (String s : arr) {
			if (StringUtils.isEmpty(s) || s.length() == 0 || "".equals(s)) {
				continue;
			}
			map.put(i + "", s.replaceAll(" {2,}", ""));// X{n,}
																	// X，至少 n 次
			i++;
			list.add(i);
		}
		return list;
	}
}
